package com.whfc.wxmp.service.impl;

import com.whfc.base.entity.AppMessage;
import com.whfc.wxmp.config.UniPushProperties;
import com.whfc.wxmp.service.UniPushService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Uni-push 2.0推送服务实现（基于云函数API规范）
 */
@Slf4j
@Service
public class UniPushServiceImpl implements UniPushService {

    @Autowired
    private UniPushProperties uniPushProperties;

    @Override
    public boolean sendSinglePush(String clientId, String title, String content, Map<String, String> extras) {
        if (!uniPushProperties.isEnabled()) {
            log.info("Uni-push推送服务未启用");
            return false;
        }

        if (clientId == null || clientId.trim().isEmpty()) {
            log.warn("Uni-push推送失败：clientId为空");
            return false;
        }

        try {
            // 构建推送请求体（按照uni-push 2.0云函数规范）
            Map<String, Object> requestBody = buildPushRequestBody(clientId, title, content, extras);

            // 发送推送请求
            return sendPushRequest(requestBody);

        } catch (Exception e) {
            log.error("发送Uni-push推送消息失败", e);
            return false;
        }
    }

    @Override
    public boolean sendPush(AppMessage message, String clientId) {
        Map<String, String> extras = buildExtras(message);
        return sendSinglePush(clientId, message.getTitle(), message.getContent(), extras);
    }

    @Override
    public int sendBatchPush(String[] clientIds, String title, String content, Map<String, String> extras) {
        int successCount = 0;
        for (String clientId : clientIds) {
            if (sendSinglePush(clientId, title, content, extras)) {
                successCount++;
            }
        }
        return successCount;
    }

    /**
     * 构建推送请求体（按照uni-push 2.0云函数规范）
     */
    private Map<String, Object> buildPushRequestBody(String clientId, String title, String content, Map<String, String> extras) {
        Map<String, Object> requestBody = new HashMap<>();

        // 客户端推送标识（必填）
        requestBody.put("cids", clientId);

        // 通知栏标题和内容
        requestBody.put("title", title);
        requestBody.put("content", content);

        // 自定义payload数据
        Map<String, Object> payload = new HashMap<>();
        if (extras != null && !extras.isEmpty()) {
            // 将扩展参数转换为payload格式
            Map<String, Object> customPayload = new HashMap<>();
            customPayload.put("url", extras.getOrDefault("url", "/pages/message/home/home"));
            customPayload.put("isHomePage", Boolean.parseBoolean(extras.getOrDefault("isHomePage", "false")));
            customPayload.put("warnType", Integer.parseInt(extras.getOrDefault("warnType", "0")));
            
            // 添加其他扩展参数
            payload.putAll(customPayload);
        } else {
            // 默认payload
            payload.put("url", "/pages/message/home/home");
            payload.put("isHomePage", false);
            payload.put("warnType", 0);
        }
        requestBody.put("payload", payload);

        return requestBody;
    }

    /**
     * 构建扩展参数
     */
    private Map<String, String> buildExtras(AppMessage message) {
        Map<String, String> extras = new HashMap<>();
        extras.put("moduleType", String.valueOf(message.getModuleType()));
//        extras.put("msgObjectId", message.getMsgObjectId() != null ? message.getMsgObjectId() : "");
//        extras.put("deptId", String.valueOf(message.getDeptId()));
        extras.put("time", message.getTime() != null ? String.valueOf(message.getTime().getTime()) : "");
        extras.put("msgChannel", String.valueOf(message.getMsgChannel()));
//        extras.put("toUserId", String.valueOf(message.getToUserId()));
//        extras.put("toUserPhone", message.getToUserPhone() != null ? message.getToUserPhone() : "");
        
        // 添加payload相关字段
        extras.put("url", "/pages/message/home/home");
        extras.put("isHomePage", "false");
        extras.put("warnType", String.valueOf(message.getModuleType()));
        
        return extras;
    }

    /**
     * 发送推送请求
     */
    private boolean sendPushRequest(Map<String, Object> requestBody) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 使用云函数接口
            String url = uniPushProperties.getApiUrl();

            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

            StringEntity entity = new StringEntity(com.alibaba.fastjson.JSONObject.toJSONString(requestBody), "UTF-8");
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity());

            if (response.getStatusLine().getStatusCode() == 200) {
                com.alibaba.fastjson.JSONObject jsonResponse = com.alibaba.fastjson.JSONObject.parseObject(responseBody);
                String errCode = jsonResponse.getString("errCode");
                if ("0".equals(errCode)) {
                    log.info("Uni-push推送消息发送成功: {}", responseBody);
                    return true;
                } else {
                    log.error("Uni-push推送消息发送失败，错误码: {}, 错误信息: {}",
                             errCode, jsonResponse.getString("errMsg"));
                }
            } else {
                log.error("Uni-push推送消息发送失败，HTTP状态码: {}, 响应: {}",
                         response.getStatusLine().getStatusCode(), responseBody);
            }

            return false;

        } catch (Exception e) {
            log.error("发送Uni-push推送请求异常", e);
            return false;
        }
    }
}